package com.lucene.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.dalin.common.utils.TextUtils;

public class LuceneIndexer {
	// 索引器对象
	private IndexWriter writer = null;

	// 在构造函数中建立索引器
	public LuceneIndexer() {
		try {
			writer = new IndexWriter(FSDirectory.open(new File(
					Constants.INDEX_STORE_PATH)), new StandardAnalyzer(
					Version.LUCENE_36), true,
					IndexWriter.MaxFieldLength.LIMITED);// 有变化的地方
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Document getDocument(File f) throws Exception {
		// 生成文档对象
		Document doc = new Document();
		// 添加索引内容
		doc.add(new Field("content", TextUtils.readNoLine(f, "gbk"), Field.Store.YES,
				Field.Index.ANALYZED));// Lucene3.0有变化的地方
		doc.add(new Field("path", f.getAbsolutePath(), Field.Store.YES,
				Field.Index.ANALYZED));// Lucene3.0有变化的地方
		return doc;
	}

	public void writeToIndex() throws Exception {
		File folder = new File(Constants.INDEX_FILE_PATH);
		if (folder.isDirectory()) {
			String[] files = folder.list();
			for (int i = 0; i < files.length; i++) {
				File file = new File(folder, files[i]);
				Document doc = getDocument(file);
				System.out.println("正在建立索引：" + file + " ");
				// 添加索引文件
				writer.addDocument(doc);
			}
		} else {
			System.out.println("-----folder.isDirectory():false.");
		}
		System.out.println("numDocs"+writer.numDocs()); 
	}

	public void close() throws Exception {
		writer.close();
	}

	public static void main(String[] args) throws Exception {
		// 声明一个对象
		LuceneIndexer indexer = new LuceneIndexer();
		// 建立索引
		Date start = new Date();
		indexer.writeToIndex();
		Date end = new Date();
		System.out
				.println("建立索引用时：" + (end.getTime() - start.getTime()) + "毫秒");
		 
		// 关闭索引器
		indexer.close();
	}
}
